import 'dart:math';

import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:gameplay_flutter/lib_basemodel/discover/comment_entity.dart';
import 'package:gameplay_flutter/lib_baseview/widget/dialogs.dart';
import 'package:gameplay_flutter/lib_im/index.dart';
import 'package:gameplay_flutter/lib_user/user_manager.dart';
import 'package:gameplay_flutter/m_me/user_details_page/user_details_page.dart';
import 'package:get/get.dart';
import 'package:ones/ui.dart';

import '../../generated/assets.dart';
import '../../lib_baseview/theme/jr.dart';
import '../../lib_chat/chat/index.dart';
import '../../resource/language/generated/l10n.dart';
import '../sel_friend/sel_friend_view.dart';
import 'post_detail_logic.dart';

class PostDetailPage extends StatelessWidget {
  PostDetailPage({int? id, Key? key}) : super(key: key) {
    logic = Get.put(PostDetailLogic(), tag: id?.toString());
  }

  late final PostDetailLogic logic;

  @override
  Widget build(BuildContext context) {

    TextDirection currentDirection = Directionality.of(context);
    bool isRTL = currentDirection == TextDirection.rtl;

    return Obx(() {
      return Scaffold(
        backgroundColor: Colors.white,
        body: SafeArea(
          child: Stack(
            children: [
              Row(
                children: [
                  JR.img(Assets.discoverBack, width: 40, height: 40).onClick(
                    () {
                      Get.back();
                    },
                  ),
                  SizedBox(width: 10),
                  JR
                      .img(logic.moment().userHeadUrl, fit: BoxFit.cover, width: 30, height: 30)
                      .roundedRect(90)
                      .onClick(() => Get.to(() => UserDetailsPage(userId: logic.moment().userId.toString()))),
                  SizedBox(width: 8),
                  Text(logic.moment().userNickname).fontSize(18),
                  const Spacer(),
                  Visibility(
                    visible: UserManager.instance.id != logic.moment().userId,
                    child: Visibility(
                      visible: logic.moment().isAttention != 1,
                      replacement: Text(T.current.discover8_unfollowed)
                          .fontSize(14)
                          .colorInt(0xff8A72FE)
                          .paddingSymmetric(horizontal: 9, vertical: 5)
                          .borderIs(radius: 36, color: const Color(0xff8A72FE))
                          .onClick(() {
                        logic.attention();
                      }),
                      child: Text(T.current.discover9_follow)
                          .fontSize(14)
                          .colorInt(0xffF2F2F2)
                          .paddingSymmetric(horizontal: 9, vertical: 5)
                          .backgroundColorInt(0xff8A72FE)
                          .roundedRect(36)
                          .onClick(() {
                        logic.attention();
                      }),
                    ),
                  ),
                  SizedBox(width: 19),
                  Image.asset(Assets.discoverShare, width: 24, height: 24).onClick(() async {
                    var user = await Get.to(() => SelFriendPage(), arguments: true);
                    if (user is FriendModel) {
                      debugPrint("发送分享消息： ${user}");
                      ImManager.of.sendShareMessage(
                        targetId: user.imId?.toString() ?? "",
                        id: logic.moment().id.toString(),
                        type: logic.moment().type,
                        image: logic.moment().cover ?? "",
                        title: logic.moment().titleStr,
                        avatar: user.headPortraitsUrl ?? "",
                        nickname: user.nickname ?? "",
                      );
                      showToast(T.current.discover9_share_success);
                    }
                  }),
                ],
              ).paddingOnly(left: 8, top: 5, bottom: 5, right: 8),
              SingleChildScrollView(
                controller: logic.scrollController,
                child: Column(
                  children: [
                    CarouselSlider(
                      items: logic.moment().files.map((e) => e.url).map((url) {
                        return Builder(builder: (BuildContext context) {
                          return Container(
                            width: MediaQuery.of(context).size.width,
                            // margin: EdgeInsets.symmetric(horizontal: 5.0),
                            decoration: BoxDecoration(
                              color: Colors.white,
                            ),
                            child: JR
                                .img(
                              url,
                              width: MediaQuery.of(context).size.width,
                              // height: logic.imageHeight(),
                              fit: BoxFit.contain,
                            )
                              ,
                          );
                        });
                      }).toList(),
                      options: CarouselOptions(
                        height: logic.imageHeight(),
                        autoPlay: false,
                        // 自动播放
                        // aspectRatio: 16 / 9,
                        // 宽高比
                        viewportFraction: 1.0,
                        enlargeCenterPage: false,
                        onPageChanged: (index, reason) {
                          logic.currentIndex(index);
                        },
                      ),
                    ).maxHeight(logic.imageHeight()),
                    Visibility(
                      visible: logic.moment().files.length > 1,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: logic.moment().files.asMap().entries.map((entry) {
                          return Container(
                            width: logic.currentIndex.value == entry.key ? 10 : 5,
                            height: 4,
                            decoration: BoxDecoration(
                              shape: BoxShape.rectangle,
                              color: logic.currentIndex.value == entry.key
                                  ? const Color(0xff8A72FE)
                                  : const Color(0xffE4E4E4),
                            ),
                          ).roundedRect(1.84).marginSymmetric(horizontal: 2, vertical: 6);
                        }).toList(),
                      ),
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const SizedBox(height: 16),
                        Text(logic.moment().title).fontSize(20),
                        const SizedBox(height: 5),
                        Text.rich(TextSpan(
                          children: [
                            ...logic.moment().contentInfoList.map(
                              (e) {
                                if (e.type == 1) {
                                  return TextSpan(
                                    text: "@${e.text}",
                                    style: const TextStyle(color: Color(0xff8A72FE), fontSize: 13),
                                    recognizer: TapGestureRecognizer()
                                      ..onTap = () {
                                        logic.messageFocus.unfocus();
                                        Get.to(() => UserDetailsPage(userId: e.userId.toString()));
                                      },
                                  );
                                } else {
                                  return TextSpan(
                                    text: e.text == "#${logic.moment().topicName}"
                                        ? ''
                                        : e.text.replaceAll("#${logic.moment().topicName}", ""),
                                    style: const TextStyle(fontSize: 13),
                                  );
                                }
                              },
                            ),
                          ],
                        )),
                        const SizedBox(height: 18),
                        Visibility(
                          visible: logic.moment().topicName.isNotEmpty,
                          child: Row(
                            children: [
                              Text("#${logic.moment().topicName}")
                                  .fontSize(12)
                                  .colorInt(0xff8A72FE)
                                  .paddingSymmetric(horizontal: 12, vertical: 3)
                                  .backgroundColorInt(0xffF8F1FF)
                                  .roundedRect(36)
                                  .marginRight(8),
                              // ...logic.moment().aboutList.map(
                              //       (e) => Text("#${e}")
                              //           .fontSize(12)
                              //           .colorInt(0xff8A72FE)
                              //           .paddingSymmetric(horizontal: 12, vertical: 3)
                              //           .backgroundColorInt(0xffF8F1FF)
                              //           .roundedRect(36)
                              //           .marginRight(8),
                              //     ),
                            ],
                          ).marginBottom(20),
                        ),
                        Visibility(
                          visible: logic.moment().cityName.isNotEmpty,
                          child: Row(
                            children: [
                              JR.img(Assets.discoverGrayLocation, width: 18, height: 20).marginRight(4),
                              Text(logic.moment().cityName).colorInt(0xffC1C1C1).fontSize(18),
                            ],
                          ),
                        ),
                        const SizedBox(height: 18),
                        Row(
                          children: [
                            Text(logic.moment().timeStr).colorInt(0xffC1C1C1).fontSize(12).marginRight(6),
                            Text(logic.moment().countryName).colorInt(0xffC1C1C1).fontSize(12).marginRight(6),
                          ],
                        ).marginBottom(16),
                        Text("${logic.moment().comments} ${T.current.discover3_video}")
                            .colorInt(0xffA8A8A8)
                            .fontSize(14)
                            .marginRight(6),
                        const SizedBox(height: 8),
                        ListView.builder(
                          padding: EdgeInsets.zero,
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          itemCount: logic.comments.length,
                          itemBuilder: (context, index) {
                            var comment = logic.comments[index];
                            return commentView(comment);
                          },
                        ),
                      ],
                    ).paddingSymmetric(horizontal: 16),
                  ],
                ),
              ).height(Get.height - 80 - 80 - MediaQuery.of(context).padding.bottom).marginTop(50),
              Column(
                children: [
                  Row(
                    children: [
                      Row(
                        children: [
                          Directionality(
                            textDirection: isRTL ? TextDirection.rtl : TextDirection.ltr,
                            child: TextField(
                              textDirection: TextDirection.ltr,
                              textAlign: isRTL ? TextAlign.end : TextAlign.start,
                              controller: logic.messageController,
                              focusNode: logic.messageFocus,
                              onTap: () {
                                logic.hintText(T.current.discover3_say_something);
                                logic.showEmojiView(false);
                                logic.commentId = null;
                              },
                              onChanged: (value) {
                                if (value.isNotEmpty) {
                                  logic.sendEnable(true);
                                } else {
                                  logic.sendEnable(false);
                                }
                                if (value.isNotEmpty && value.length > logic.previewText.length && value.endsWith(' @')) {
                                  logic.atUser();
                                }
                                logic.previewText = value;
                              },
                              onSubmitted: (value) {
                                logic.discoverComment();
                              },
                              // maxLines: 2,
                              style: const TextStyle(color: Color(0xff1B1B1B), fontSize: 14),
                              decoration: InputDecoration(
                                  hintText: logic.hintText(),
                                  hintStyle: const TextStyle(color: Color(0xffd8d8d8), fontSize: 14),
                                  hintTextDirection: TextDirection.ltr,
                                  border: InputBorder.none,
                                  isCollapsed: true,
                                  contentPadding: const EdgeInsets.symmetric(vertical: 7)),
                            ).expanded(),
                          ),
                          Row(
                            children: [
                              Image.asset(Assets.discoverAt, width: 28, height: 28).onClick(() {
                                logic.atUser();
                              }).marginRight(3),
                              Image.asset(Assets.discoverEmoji, width: 28, height: 28).onClick(
                                () {
                                  if (!logic.showEmojiView()) {
                                    logic.messageFocus.unfocus();
                                  }
                                  logic.showEmojiView.toggle();
                                },
                              ).marginRight(3),
                            ],
                          ),
                        ],
                      ).paddingSymmetric(horizontal: 13).backgroundColorInt(0xffF2F2F2).roundedRect(90).expanded(),
                      SizedBox(width: 12),
                      Visibility(
                        visible: !logic.showSendButton(),
                        replacement: Opacity(
                          opacity: logic.sendEnable() ? 1 : 0.4,
                          child: Row(
                            children: [
                              Image.asset(Assets.discoverPost, width: 18, height: 18).marginRight(4),
                              Text(T.current.c_send).fontSize(16).colorInt(0xffffffff).fontWeight(FontWeight.w600),
                            ],
                          )
                              .paddingSymmetric(horizontal: 15, vertical: 7)
                              .backgroundColorInt(0xff8A72FE)
                              .roundedRect(90)
                              .onClick(() {
                            logic.discoverComment();
                          }),
                        ),
                        child: Row(
                          children: [
                            Column(
                              children: [
                                Image.asset(logic.moment().isLike ? Assets.discoverStar : Assets.discoverStarGrey,
                                        width: 32, height: 32)
                                    .onClick(() {
                                  Debouncer.run("likeComment", 800.milliseconds, () {
                                    logic.like();
                                  });
                                }),
                                Text(logic.moment().likes.toString())
                                    .colorInt(0xff444444)
                                    .fontSize(14)
                                    .fontWeight(FontWeight.w500),
                              ],
                            ).marginRight(9),
                            Column(
                              children: [
                                Image.asset(Assets.discoverComment, width: 32, height: 32),
                                Text(logic.moment().comments.toString())
                                    .colorInt(0xff444444)
                                    .fontSize(14)
                                    .fontWeight(FontWeight.w500),
                              ],
                            ).onClick(
                              () {
                                logic.clickComment();
                              },
                            ),
                          ],
                        ),
                      ),
                    ],
                  ).paddingSymmetric(horizontal: 16, vertical: 5),
                  Visibility(
                    visible: logic.showEmojiView(),
                    child: MessageEmoji(
                      onTap: (emoji) => logic.messageController.text += emoji,
                    ).height(320),
                  )
                ],
              ).backgroundColor(Colors.white).positioned(bottom: 0, left: 0, right: 0),
            ],
          ).height(Get.height).onClick(
            () {
              logic.showEmojiView(false);
              logic.messageFocus.unfocus();
              logic.commentId = null;
              logic.hintText(T.current.discover3_say_something);
            },
          ),
        ),
      );
    });
  }

  Column commentView(CommentEntity comment, {bool showDivider = true, bool isReply = false}) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Material(
          color: Colors.transparent,
          shadowColor: Colors.transparent,
          child: InkWell(
            onTap: () {
              logic.showEmojiView(false);
              // logic.hintText("回复 @${comment.fromUserNickname}：");
              logic.commentId = comment.id;
              logic.messageFocus.requestFocus();
            },
            onLongPress: () {
              if (comment.fromUserId == UserManager.instance.id) {
                Get.bottomSheet(
                  Column(
                    children: [
                      Text(T.current.delete)
                          .color(Colors.black)
                          .fontSize(20)
                          .fontWeight(FontWeight.w600)
                          .paddingSymmetric(vertical: 18)
                          .onClick(() {
                        Get.back();
                        logic.deleteComment(comment.id);
                      }),
                      Container(height: 10, color: const Color(0xffFAFAFA)),
                      Text(T.current.cancel)
                          .color(const Color(0xffA8A8A8))
                          .fontSize(20)
                          .paddingSymmetric(vertical: 18)
                          .onClick(() {
                        Get.back();
                      }),
                    ],
                  )
                      .backgroundColor(Colors.white)
                      .roundedRectVertical(18, 0)
                      .height(120 + Get.bottomBarHeight / Get.pixelRatio),
                );
              }
            },
            highlightColor: Colors.transparent,
            splashColor: Colors.transparent,
            focusColor: Colors.transparent,
            hoverColor: Colors.transparent,
            enableFeedback: false,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    JR
                        .img(comment.fromUserHeadUrl, fit: BoxFit.cover, width: 24, height: 24)
                        .roundedRect(90)
                        .onClick(() => Get.to(() => UserDetailsPage(userId: comment.fromUserId.toString())))
                        .marginRight(6),
                    Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(comment.fromUserNickname).colorInt(0xffC1C1C1).fontSize(12).marginBottom(1),
                        Row(
                          children: [
                            Text.rich(TextSpan(
                              children: [
                                if (comment.isReply == 1)
                                  TextSpan(
                                    text: "${T.current.discover9_reply} ",
                                    style: TextStyle(color: Color(0xff8A72FE), fontSize: 13),
                                  ),
                                if (comment.isReply == 1)
                                  TextSpan(
                                    text: comment.toUserNickname + ": ",
                                    style: const TextStyle(color: Color(0xffC1C1C1), fontSize: 13),
                                  ),
                                ...comment.contentInfoList.map(
                                  (e) {
                                    if (e.type == 1) {
                                      return TextSpan(
                                        text: "@${e.text}",
                                        style: const TextStyle(color: Color(0xff8A72FE), fontSize: 13),
                                        recognizer: TapGestureRecognizer()
                                          ..onTap = () {
                                            logic.messageFocus.unfocus();
                                            Get.to(() => UserDetailsPage(userId: e.userId.toString()));
                                          },
                                      );
                                    } else {
                                      return TextSpan(
                                        text: e.text,
                                        style: const TextStyle(fontSize: 13),
                                      );
                                    }
                                  },
                                ),
                              ],
                            )).expanded(),
                          ],
                        ).backgroundColor(Colors.transparent),
                        Text(comment.timeStr).colorInt(0xffC1C1C1).fontSize(10).marginBottom(1),
                      ],
                    ).marginRight(4).expanded(),
                    Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Image.asset(comment.isLike == 1 ? Assets.discoverStar : Assets.discoverStarGrey,
                                width: 24, height: 24)
                            .marginBottom(1),
                        Text(comment.likes.toString()).colorInt(0xff444444).fontSize(10),
                      ],
                    ).onClick(() {
                      Debouncer.run("likeComment", 800.milliseconds, () {
                        logic.likeComment(comment);
                      });
                    }).marginRight(20),
                  ],
                ),
                const SizedBox(height: 4),
                Visibility(visible: showDivider, child: Container(height: 1, color: const Color(0xffF2F2F2))),
              ],
            ).padding(top: 8),
          ),
        ),
        if (comment.showMode)
          ...comment.replyList.map(
            (e) => commentView(e, showDivider: false, isReply: true).marginLeft(24),
          ),
        if (!isReply && !comment.showMode)
          ...comment.replyList.sublist(0, min(1, comment.replyList.length)).map(
                (e) => commentView(e, showDivider: false, isReply: true).marginLeft(24),
              ),
        if (!isReply && !comment.showMode && comment.replyList.length > 1)
          Text(T.current.discover9_show_more_replies)
              .colorInt(0xffA397DE)
              .fontSize(10)
              .marginLeft(24)
              .marginSymmetric(vertical: 8)
              .onClick(() {
            comment.showMode = true;
            logic.comments.refresh();
          }),
      ],
    );
  }
}
